package com.demo.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;

/**
 * @author 文希
 * @create 2019-07-09 14:47
 **/
@Component
@Scope("prototype") // 每个事物都是新的实例，目的解决线程安全问题 多实例
public class TransactionUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(TransactionUtils.class);

    private TransactionStatus transactionStatus;

    // 获取事务源
    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;

    // 开启事务
    public TransactionStatus begin() {
        LOGGER.info("开启事务");
        transactionStatus = dataSourceTransactionManager.getTransaction(new DefaultTransactionAttribute());
        return transactionStatus;
    }

    // 提交事务
    public void commit(TransactionStatus transactionStatus) {
        LOGGER.info("提交事务");
        dataSourceTransactionManager.commit(transactionStatus);
    }

    // 回滚事务
    public void rollback() {
        LOGGER.info("回滚事务。。。");
        dataSourceTransactionManager.rollback(transactionStatus);
    }
}
